package net.hserver.sync.file;

import cn.hserver.core.queue.HServerQueue;
import net.hserver.sync.config.EventConst;
import net.hserver.sync.config.FileState;
import net.hserver.sync.entity.SyncWebDavConfigEntity;
import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;
import org.apache.commons.io.monitor.FileAlterationObserver;

import java.io.File;

public class FileListener extends FileAlterationListenerAdaptor {

    private final SyncWebDavConfigEntity syncWebDavConfigEntity;

    public FileListener(SyncWebDavConfigEntity syncWebDavConfigEntity) {
        this.syncWebDavConfigEntity = syncWebDavConfigEntity;
    }

    public String getLocalPath() {
        return syncWebDavConfigEntity.getLocalPath();
    }
    public String getId() {
        return syncWebDavConfigEntity.getId();
    }

    @Override
    public void onStart(FileAlterationObserver observer) {
        super.onStart(observer);
    }

    @Override
    public void onDirectoryCreate(File directory) {
        String remotePath = syncWebDavConfigEntity.localToRemotePath(directory.getAbsolutePath());
        HServerQueue.sendQueue(EventConst.LOCAL_CHANGE_EVENT,getId() , FileState.onDirectoryCreate, directory.getAbsolutePath(), remotePath);
    }

    @Override
    public void onDirectoryChange(File directory) {
    }

    @Override
    public void onDirectoryDelete(File directory) {
        if (syncWebDavConfigEntity.getSyncMode()== SyncWebDavConfigEntity.SyncMode.sync) {
            String remotePath = syncWebDavConfigEntity.localToRemotePath(directory.getAbsolutePath());
            HServerQueue.sendQueue(EventConst.LOCAL_CHANGE_EVENT, getId(), FileState.onDirectoryDelete, directory.getAbsolutePath(),remotePath);
        }
    }

    @Override
    public void onFileCreate(File file) {
        String remotePath = syncWebDavConfigEntity.localToRemotePath(file.getAbsolutePath());
        HServerQueue.sendQueue(EventConst.LOCAL_CHANGE_EVENT, getId() , FileState.onFileCreate, file.getAbsolutePath(), remotePath);
    }

    @Override
    public void onFileChange(File file) {
        String remotePath = syncWebDavConfigEntity.localToRemotePath(file.getAbsolutePath());
        HServerQueue.sendQueue(EventConst.LOCAL_CHANGE_EVENT, getId() , FileState.onFileChange, file.getAbsolutePath(), remotePath);
    }

    @Override
    public void onFileDelete(File file) {
        if (syncWebDavConfigEntity.getSyncMode()== SyncWebDavConfigEntity.SyncMode.sync) {
            String remotePath = syncWebDavConfigEntity.localToRemotePath(file.getAbsolutePath());
            HServerQueue.sendQueue(EventConst.LOCAL_CHANGE_EVENT, getId(), FileState.onFileDelete, file.getAbsolutePath(), remotePath);
        }
    }

    @Override
    public void onStop(FileAlterationObserver observer) {
        super.onStop(observer);
    }
}
